<template>
<div>



	<Row>
		<Form ref="formInline"  inline>
	        <FormItem >
	            <Select v-model="ts" style="width:700px;" multiple @on-change="selectOnChange">
			        <Option v-for="item in tables" :value="item.table_name" :key="item.table_name">{{ item.table_name }}</Option>
			    </Select>
	        </FormItem>

	        <FormItem >
	            <Button type="success" @click="showOpt">操作</Button>
	        </FormItem>
	    </Form>
	</Row>

	<Row>
		
	</Row>


	<Row>

		<Col span="6" v-for="(item, index) in selectTables" :key="index"
		class="text-center"
		>
			{{item}}
			<dbtable :obj="tabledata[item]"></dbtable>
		</Col>

	</Row>

	<!-- :mask-closable="false" -->
	<Drawer :closable="false" width="1140" v-model="opt" >

		<Form :label-width="80" inline>
	        <FormItem label="接口名称">
	        	<span v-if="$route.params.name">{{pagename}}</span>
	            <Input v-else type="text" v-model="pagename" />
	        </FormItem>
	    </Form>

	    <Row>
	    	<Col span="8"><Alert>列表：GET 请求 /v1/pn/api?service={{pagename}}</Alert></Col>
	    	<Col span="8"><Alert>详情：GET 请求 /v1/pn/api/[info条件]?service={{pagename}}</Alert></Col>
	    	<Col span="8"><Alert>创建：POST 请求 /v1/pn/api?service={{pagename}}</Alert></Col>
	    </Row>
	    <Row>
	    	<Col span="8"><Alert>更新：PUT 请求 /v1/pn/api/[info条件]?service={{pagename}}</Alert></Col>
	    	<Col span="8"><Alert>删除：DELETE 请求 /v1/pn/api/[info条件]?service={{pagename}}</Alert></Col>
	    </Row>
	    
	    
	    
	    

		<!-- 列 -->
		<Table :columns="columns" :data="optTableCol" >
			<template slot-scope="{ row, index }" slot="tname">
		      <span>{{ row.tname }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="name">
		      <span>{{ row.name }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="asname">
		    	<Input type="text" v-model="editAsname" 
		    	v-if="editIndex === index" />
      			<span v-else>{{ row.asname }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="title">
		    	<Input type="text" v-model="editTitle" 
		    	v-if="editIndex === index" />
      			<span v-else>{{ row.title }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="show">
		    	<Select v-model="editShow" v-if="editIndex === index">
			        <Option value="1" :key="1">显示</Option>
			        <Option value="0" :key="0">隐藏</Option>
			    </Select>
      			<span v-else>{{ show[parseInt(row.show)] }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="type">
		    	<Select v-model="editType" v-if="editIndex === index">
			        <Option v-for="item in typeList" 
			        :value="item.value" 
			        :key="item.value">{{ item.label }}</Option>
			    </Select>
      			<span v-else>{{ row.type }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="action">
				<div v-if="editIndex === index">
					<Button icon="md-checkmark"
					@click="handleSave(index)">保存</Button>
					<Button icon="md-close"
					@click="editIndex = -1">取消</Button>
				</div>
				<div v-else>
					<Button icon="ios-cube-outline" 
		      		@click="handleEdit(row, index)"></Button>
		      		<Button icon="md-arrow-down" 
		      		@click="colDown(row, index)"></Button>
					<Button icon="md-arrow-up" 
					@click="colUp(row, index)"></Button>
					<Button icon="md-remove" 
					@click="colRemove(row, index)"></Button>
				</div>
		    </template>
		</Table>

		<!-- 表 -->
		<Table :columns="columns1" :data="optTableConn" class="mt10" >
			<template slot-scope="{ row, index }" slot="master">
		      <span >{{ row.master }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="mastercol">
		    	<Select v-model="editmastercol" v-if="editIndex1 === index">
			        <Option v-for="item in tabledata[row.master].data" 
			        :value="item.column_name" 
			        :key="item.column_name">{{ item.column_name }}</Option>
			    </Select>

			    <span v-else>{{ row.mastercol }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="what">
		      	<Select v-model="editTableWhat" v-if="editIndex1 === index">
			        <Option v-for="item in whatList" 
			        :value="item.label" 
			        :key="item.label">{{ item.label }}</Option>
			    </Select>
			    <span v-else>{{row.what}}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="second">
		      <span>{{ row.second }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="secondcol">
		    	<Select v-model="editsecondcol" v-if="editIndex1 === index">
			        <Option v-for="item in tabledata[row.second].data" 
			        :value="item.column_name" 
			        :key="item.column_name">{{ item.column_name }}</Option>
			    </Select>
			    <span v-else>{{ row.secondcol }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="action">
				<div v-if="editIndex1 === index">
					<Button icon="md-checkmark"
					@click="handleSave1(index)">保存</Button>
					<Button icon="md-close"
					@click="editIndex1 = -1"></Button>
				</div>
				<div v-else>
					<Button icon="ios-cube-outline" 
		      		@click="handleEdit1(row, index)"></Button>
				</div>
		    </template>
		</Table>

		<!-- 条件 -->
		<Table :columns="columns2" :data="optTableCondition" class="mt10" >
			<template slot-scope="{ row, index }" slot="table">
		      <span >{{ row.table }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="col">
		      <span>{{ row.col }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="what">
		      	<Select v-model="eidtConditionWhat" v-if="editIndex2 === index">
			        <Option v-for="item in whatList1" 
			        :value="item.label" 
			        :key="item.label">{{ item.label }}</Option>
			    </Select>
			    <span v-else>{{row.what}}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="value">
		    	<Input type="text" v-model="eidtConditionValue" 
		    	v-if="editIndex2 === index" />
		      	<span v-else>{{ row.value }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="action">
		    	<div v-if="editIndex2 === index">
					<Button icon="md-checkmark"
					@click="handleSave2(index)">保存</Button>
					<Button icon="md-close"
					@click="editIndex2 = -1"></Button>
				</div>
				<div v-else>
					<Button icon="ios-cube-outline" 
		      		@click="handleEdit2(row, index)"></Button>
		      		<Button icon="md-arrow-down" 
		      		@click="conditionDown(row, index)"></Button>
		     		<Button icon="md-arrow-up" 
		      		@click="conditionUp(row, index)"></Button>
		      		<Button icon="md-close" 
		      		@click="conditionRemove(row, index)"></Button>
				</div>
		    </template>
		    
		</Table>




		<!-- 详情条件，如果不填默认id，只能填一个，默认成主表id -->
		<Table :columns="columns3" :data="optTableInfoCondition" class="mt10" >
			<template slot-scope="{ row, index }" slot="table">
				<Select v-model="eidtInfoConditionTable" v-if="editIndex3 === index">
			        <Option v-for="item in selectTables" 
			        :value="item" 
			        :key="item">{{ item }}</Option>
			    </Select>
			    <span v-else>{{ row.table }}</span>
		    </template>

		    <template slot-scope="{ row, index }" slot="col">
		    	<Select v-model="eidtInfoConditionCol" v-if="editIndex3 === index">
			        <Option v-for="item in tabledata[eidtInfoConditionTable].data" 
			        :value="item.column_name" 
			        :key="item.column_name">{{ item.column_name }}</Option>
			    </Select>
		      	<span v-else>{{ row.col }}</span>
		    </template>
		   

		    <template slot-scope="{ row, index }" slot="action">
		    	<div v-if="editIndex3 === index">
					<Button icon="md-checkmark"
					@click="handleSave3(index)">保存</Button>
					<Button icon="md-close"
					@click="editIndex3 = -1"></Button>
				</div>
				<div v-else>
					<Button icon="ios-cube-outline" 
		      		@click="handleEdit3(row, index)"></Button>
				</div>
		    </template>
		    
		</Table>

		<Divider />

		<Row >
			<Button type="primary" @click="save">保存</Button>
			<Button type="success" @click="continueSelect">继续选择</Button>
		</Row>
		
    </Drawer>



	<!-- <Table border :columns="columns1" :data="data1" draggable 
	@on-drag-drop="drop"
	></Table> -->

</div>
</template>

<script>
import Vue from 'vue'
import dbtable from './components/dbtable'

export default {
	
	name : 'dbtableconfig',
	
	data () {
		return {
			draggable : true,

			show : ['隐藏', '显示'],

			pagename : '',

			id : undefined,

		  	columns: [
		  	  {
	            title: '表名',
	            slot: 'tname',
	          },
	          {
	            title: '列名',
	            slot: 'name',
	          },
	          {
	            title: '别名',
	            slot: 'asname',
	          },
	          {
	            title: '表头',
	            slot: 'title',
	          },
	          {
	            title: '显示',
	            slot: 'show',
	          },
	          {
	            title: '类型',
	            slot: 'type',
	          },
	          {
	            title: '操作',
	            slot: 'action',
	            width: '250px',
	          }
	        ],
	        columns1 : [
	        	{
	        		title : '主表',
	        		slot : 'master',
	        	},
	        	{
	        		title : '主表列',
	        		slot : 'mastercol',
	        	},
	        	{
	        		title : '条件',
	        		slot : 'what',
	        	},
	        	{
	        		title : '副表',
	        		slot : 'second',
	        	},
	        	{
	        		title : '副表列',
	        		slot : 'secondcol',
	        	},
	        	{
					title: '操作',
					slot: 'action',
				},
	        ],

	        columns2 : [
	        	{
	        		title : '表',
	        		slot : 'table',
	        	},
	        	{
	        		title : '列',
	        		slot : 'col',
	        	},
	        	{
	        		title : '条件',
	        		slot : 'what',
	        	},
	        	{
	        		title : '值',
	        		slot : 'value',
	        	},
	        	{
		            title: '操作',
		            slot: 'action',
		            width: '250px',
		        }
	        ],


	        columns3 : [
	        	{
	        		title : '表名',
	        		slot : 'table',
	        	},
	        	{
	        		title : '列名',
	        		slot : 'col',
	        	},
	        	{
		            title: '操作',
		            slot: 'action',
		            width: '250px',
		        },
	        ],

	        editIndex: -1,  // 列
	        editAsname : '',
	        editTitle : '',
	        editShow : '',
	        editType : '',


	        editIndex1 : -1,	//表格
	        editmastercol : '',
	        editsecondcol : '',
	        editTableWhat : '',


	        editIndex2 : -1,	//条件
	        eidtConditionWhat : '',
	        eidtConditionValue : '',



	        editIndex3 : -1,	//info条件
	        eidtInfoConditionTable : '',
	        eidtInfoConditionCol : '',

	        initData : {}, //进来的数据。

	        tables : [],
	        ts : [],

	        tabledata : {},

	        selectTables : [],

	        opt : false,

	        optTableCol : [],

	        optTableConn : [],

	        optTableCondition : [],

	        optTableInfoCondition : [],


	        whatList : [
	        	{
	        		label : ' left join '
	        	},
	        	{
	        		label : ' right join '
	        	},
	        	{
	        		label : ' inner join '
	        	},

	        ],

	        whatList1 : [
	        	{
	        		label : ' = '
	        	},
	        	{
	        		label : ' > '
	        	},
	        	{
	        		label : ' < '
	        	},
	        	{
	        		label : ' like '
	        	},
	        	
	        ],


	        typeList : [
	        	{
	        		label : '文本',
	        		value : 'text',
	        	},
	        	{
	        		label : 'json',
	        		value : 'json',
	        	},
	        	{
	        		label : '图片',
	        		value : 'image',
	        	},
	        ]
		}
	},

	props : {

	},

	components : {
		dbtable,
	},

	computed : {
		
	},

	methods : {
		
		init () {


			console.log(this.$route.query.name);


			if(this.$route.query.name != undefined){
				this.pagename = this.$route.query.name;


				this.$http({
					fun : '/v1/pn/api/' + this.$route.query.name,
					service : 'page',
					requestType : 'GET',
					cb : res => {
						console.log('asdasdasdadsads');
						console.log(res);

						if(res != undefined){
							const json = JSON.parse(res.json);
							console.log(json);

							this.initData = json;
							this.id = res.id;

							//this.ts.push(json.table.master);
							//this.selectTables.push(json.table.master);


							this.initTableData(json);


							this.opt = true;

						}
					}
				});

			}

			

			this.$http({
				fun : 'tables',
				cb : res => {
					console.log(res);
					this.tables = res;
				}
			});
		},

		selectOnChange (item) {
			console.log(item);
			this.selectTables = item;

			this.selectTables.forEach(item => {

				if(this.tabledata[item] == undefined){
					this.$http({
						fun : 'cols',
						tablename : item,
						cb : res => {

							let selection = [];

							if(this.initData.col){
								res.forEach(item1 => {
									this.initData.col.forEach(item2 => {
										if(item2.tname == item && item2.cname == item1.column_name){
											item1['_checked'] = true;
											item1['_disabled'] = true;
											selection.push({column_name : item2.cname});
										}
									})
								})
							}

							let obj = {
								data : res,
								selection,
							}
							Vue.set(this.tabledata, item, obj);
						}
					});
				}
				
			});

		},

		showOpt () {
			
			console.log('开始');
			console.log(this.tabledata);
			console.log(this.optTableCol);


			//this.optTableCol = [];
			this.selectTables.forEach(item => {
				this.tabledata[item].selection.forEach(item1 => {
					let obj = {
						name : item1.column_name,
						tname : item,
						asname : '',
						title : '',
						show : '1',
						type : 'text',
					};
					this.optTableCol.push(obj);
				});
			});
			
			//this.optTableConn = [];
			if(this.optTableConn.length == 0 && this.selectTables.length > 1){
				const master = this.selectTables[0];
				this.selectTables.forEach((item, index) => {
					if(index != 0){
						let obj = {
							master,
							second : item,
							what : ' left join ',
							on : '',
							mastercol : this.tabledata[master].data[0].column_name,
							secondcol : this.tabledata[item].data[0].column_name,
						};
						this.optTableConn.push(obj);
					}
				});
			}else if(this.selectTables.length == 1){
				this.optTableConn = [];
			}


			this.selectTables.forEach(item => {
				this.tabledata[item].selection.forEach(item1 => {
					let obj = {
						col : item1.column_name,
						table : item,
						what : ' = ',
						value : '?',
						condition : ' and ',
					};
					this.optTableCondition.push(obj);
				});
			});

			if(this.optTableInfoCondition.length == 0){
				this.optTableInfoCondition.push({
					table : this.selectTables[0],
					col : this.tabledata[this.selectTables[0]].data[0].column_name,
				});
			}
			this.opt = true;
		},


		
		colRemove (row, index) {
			this.optTableCol.splice(index,1);
		},
		colDown (row, index) {
			this.optTableCol[index] = this.optTableCol.splice(index + 1, 1, this.optTableCol[index])[0];
		},
		colUp (row, index) {
			this.optTableCol[index] = this.optTableCol.splice(index - 1, 1, this.optTableCol[index])[0];
		},

		conditionRemove (row, index) {
			this.optTableCondition.splice(index,1);
		},
		conditionDown (row, index) {
			this.optTableCondition[index] = this.optTableCondition.splice(index + 1, 1, this.optTableCondition[index])[0];
		},
		conditionUp (row, index) {
			this.optTableCondition[index] = this.optTableCondition.splice(index - 1, 1, this.optTableCondition[index])[0];
		},

		//继续选择
		continueSelect () {

			console.log('继续选择');

			console.log(this.optTableCol);

			let obj = {};

			this.optTableCol.forEach(item => {
				if(obj[item.tname] == undefined){
					obj[item.tname] = {};
				}
				obj[item.tname][item.name] = '1';
			});

			this.selectTables.forEach(item => {
				this.tabledata[item].selection = [];
				this.tabledata[item].data.forEach((item1, index) => {
					delete item1['_disabled'];
					delete item1['_checked'];
					if(obj[item][item1.column_name]){
						Vue.set(item1, '_disabled', true);
						// this.tabledata[item].selection.push({
						// 	column_name : item1.column_name
						// })
					}
				});
			});

			this.opt = false;
		},


		save () {

			let sql = {
				col : [],
				table : {
					master : '',
					condition : [],
				},
				where : [],
				infoWhere : {},
			};

			this.optTableCol.forEach(item => {
				sql.col.push({
					tname : item.tname,
					cname : item.name,
					asname : item.asname,
					title : item.title,
					show : item.show,
					type : item.type,
				})
			});

			sql.table.master = this.selectTables[0];

			this.optTableConn.forEach(item => {
				let on = [item.mastercol, item.secondcol];
				sql.table.condition.push({
					table : item.second,
					what : item.what,
					on,
				})
			});

			this.optTableCondition.forEach(item => {
				sql.where.push({
					tname : item.table,
					cname : item.col,
					what : item.what,
					value : item.value,
					condition : ' and ',
				});
			})

			sql.infoWhere = {
				tname : this.optTableInfoCondition[0].table,
				cname : this.optTableInfoCondition[0].col,
			}

			console.log(' ====== sql ======= ');
			console.log(sql);
			console.log(this.id);

			this.$http({
				fun : 'createApi',
				name : this.pagename,
				id : this.id,
				'sql' : JSON.stringify(sql),
				cb : res => {
					console.log(res);
				}
			});

		},

		handleEdit (row, index) {
			this.editAsname = row.asname;
			this.editTitle = row.title;
			this.editShow = row.show;
			this.editType = row.type;
			this.editIndex = index;
		},


		handleSave (index) {
			this.optTableCol[index].asname = this.editAsname;
			this.optTableCol[index].title = this.editTitle;
			this.optTableCol[index].show = this.editShow;
			this.optTableCol[index].type = this.editType;
			this.editIndex = -1;
		},


		handleEdit1 (row, index) {
			this.editmastercol = row.mastercol;
	        this.editsecondcol = row.secondcol;
	        this.editTableWhat = row.what;
			this.editIndex1 = index;
		},


		handleSave1 (index) {
			this.optTableConn[index].mastercol = this.editmastercol;
			this.optTableConn[index].secondcol = this.editsecondcol;
			this.optTableConn[index].what = this.editTableWhat;
			this.editIndex1 = -1;
		},


		handleEdit2 (row, index) {
	        this.eidtConditionWhat = row.what;
	        this.eidtConditionValue = row.value;
			this.editIndex2 = index;
		},


		handleSave2 (index) {
			this.optTableCondition[index].what = this.eidtConditionWhat;
			this.optTableCondition[index].value = this.eidtConditionValue;
			this.editIndex2 = -1;
		},


		handleEdit3 (row, index) {
	        this.eidtInfoConditionTable = row.table;
	        this.eidtInfoConditionCol = row.col;
			this.editIndex3 = index;
		},


		handleSave3 (index) {
			this.optTableInfoCondition[index].table = this.eidtInfoConditionTable;
			this.optTableInfoCondition[index].col = this.eidtInfoConditionCol;
			this.editIndex3 = -1;
		},


		/*

			初始化 optTableCol，optTableConn，optTableCondition, optTableInfoCondition

			先初始化tabledata，然后再selectTables，要不然更新selectTables会出发选择表格事件更新tabledata
			初始化 selectTables，tabledata，不用管tabledata中的selection

			弹出操作框，然后从操作框操作回来
		*/
		initTableData (json) {

			json.col.forEach(item => {
				this.optTableCol.push({
					name : item.cname,
					tname : item.tname,
					asname : item.asname,
					title : item.title,
					show : item.show,
					type : item.type,
				})
			});

			let tables = [];

			tables.push(json.table.master);

			json.table.condition.forEach(item => {
				this.optTableConn.push({
					second : item.table,
					what : item.what,
					on : item.on,
				});
				tables.push(item.table);
			})

			let tnames = '';
			tables.forEach(item => {
				tnames += item + ',';
			})

			this.$http({
				fun : 'cols',
				tablename : tnames,
				multiple : true,
				cb : res => {
					console.log('多个数据表');
					console.log(res);

					Object.keys(res).forEach(item => {
						Vue.set(this.tabledata, item, {
							data : res[item],
							selection : [],
						});
					})
					console.log(this.tabledata);
					this.selectTables = tables;
					this.ts = tables;
				}
			});

			json.where.forEach(item => {
				this.optTableCondition.push({
					table : item.tname,
					col : item.cname,
					what : item.what,
					value : item.value,
					condition : item.condition,
				})
			})

			this.optTableInfoCondition.push({
				table : json.infoWhere.tname,
				col : json.infoWhere.cname,
			});

		},
		
	},

	watch : {
	    
	},

	mounted () {
		this.init();
	},

}
</script>

<style scoped>

</style>
